package com.ibm.risk.irmp.rule.data;

import com.ibm.risk.irmp.common.vo.PagedParam;
import com.ibm.risk.irmp.common.vo.PagedResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class SqlDataImporter implements DataImporter {
    public static final String SQL = "SQL";
    @Autowired
    NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public String getDataAccessType() {
        return SQL;
    }

    @Override
    public <T> PagedResult<T> readData(Map<String, Object> params, PagedParam pagedParam, Class<T> dataType) {
        //sql e.g.: select a, b, c from table where c = :c
        PagedResult rst = new PagedResult<>();
        String sql = (String) params.get(SQL);
        if (pagedParam.getPageIndex() == 0) {
            String countSql = "select count(*) from (" + sql + ") t";
            Integer total = jdbcTemplate.queryForObject(countSql, params, Integer.class);
            log.info("total data to be input: {}", total);
            rst.setTotal(total);
        }
        int limit = pagedParam.getPageSize() * pagedParam.getPageIndex();
        String sqlWithLimit = sql + " limit " + pagedParam.getPageSize() + " offset " + limit;
        if (dataType != null) {
            rst.setList(jdbcTemplate.query(sqlWithLimit, params, new BeanPropertyRowMapper<>(dataType)));
        } else {
            List<?> maps = jdbcTemplate.queryForList(sqlWithLimit, params);
            rst.setList(maps);
        }
        return rst;
    }
}
